<?php
/* 
 *采购单
 */
class BuyAction extends CommonAction {
    public function _filter(&$map) {
        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
            $where['Product.name'] = array('like',"%".$key."%");//产品名称
            $where['Product.ename'] = array('like',"%".$key."%");
            $where['Product.cas'] = array('like',"%".$key."%");//条码
            $where['Buy.mano'] = array('like',"%".$key."%");//条码
            $where['_logic'] = "or";
            $map['_complex'] = $where;
        }
        
        if($_REQUEST['status'] != '' )
            $map['status'] = $_REQUEST['status'];
        if( $_REQUEST['in_qc_status'] != '' )
            $map['in_qc_status'] = $_REQUEST['in_qc_status'];
        if( $_REQUEST['exception_status'] != '' )//异常状态
            $map['exception_status'] = $_REQUEST['exception_status'];
        if( $_REQUEST['exception_status'] == 9 )//显示所有退化订单的异常状态
            $map['exception_status'] = array('in','1,2,4,6');
        if( $_REQUEST['sample_qc_status'] != '' ){
            if($_REQUEST['sample_qc_status'] == 7 )//样检订单
                $map['sample_qc_status'] =  array('between','2,6');
            else
                $map['sample_qc_status'] = $_REQUEST['sample_qc_status'];
        }
        if( $_REQUEST['pay_status'] != '' )
            $map['pay_status'] = $_REQUEST['pay_status'];

        if( $_REQUEST['priority'] != ""){
            if($_REQUEST['priority'] != 3 ){ //非催单
                 $map['priority'] = $_REQUEST['priority'];
                 $map['status'] = array('not in','8,10'); //排除已入库及作废订单
            }
            else{
                 $map['priority'] = array('between','4,6'); //催单
                 $map['status'] = array('not in','8,10'); //排除已入库及作废订单
            }
        
        }

        $sid = $_REQUEST['supplier'];
        if(!empty($sid))
            $map['sname'] = array('like',"%".$sid."%");
        if(!empty($_REQUEST['order_detail_mano']))
            $map['Order_detail.mano'] = array('like',"%".trim($_REQUEST['order_detail_mano'])."%");

           //time 
        $cond_time = array();
        if( $_REQUEST['start_time'] != '' )
          array_push($cond_time, array( 'egt' , strtotime($_REQUEST['start_time']) ) );
          //$cond_time = array( 'egt' , strtotime($_REQUEST['start_time']) );
        if( $_REQUEST['end_time'] != '' )
          array_push($cond_time, array( 'elt' , strtotime($_REQUEST['end_time']) ) );

        //选择了时间类型,并且时间不为空，则按时间进行搜索
        if( $_REQUEST['time_type'] != "" && 
          ($_REQUEST['end_time'] != '' ||  $_REQUEST['start_time'] != '' ) ){
            switch ($_REQUEST['time_type']) {
              case '1': //交货期
                $map['Order_detail.delivery_date '] = $cond_time;
                break;
              case '2': //创建时间
                $map['Buy.create_time '] = $cond_time;
                break;
              
              case '3': //收货时间
                $map['Buy.receive_time '] = $cond_time;
                break;
              
              default:  //按采购时间查询
                $map['Buy.create_time '] = $cond_time;
                break;
            }
            
        }

    }


    public function  index() {
        if(!empty($_REQUEST['order_detail_mano']) || $_REQUEST['end_time'] != '' ||  $_REQUEST['start_time'] != '' )
            parent::index('BuyOrderView');
        else if( !empty($_REQUEST['supplier']) )
            parent::index('BuySPView');
		else if( !empty($_REQUEST['keywords']) )
			parent::index('BuyView');
        else
            parent::index('Buy');
    }

    /*
    public function  index() {
        $map = $this->_search ();
        if (method_exists ( $this, '_filter' )) {
            $this->_filter ( $map );
        }
        $model = D ('BuyView');
        if (! empty ( $model )) {
            $this->_list(D('BuyView'), $map, $sortBy = '', $asc = false,true);
        }
        $this->display ();
        return;
    
    } */

    public function _before_add()
    {
        $this->assign('logicompany',C('chinalogi'));
        $this->assign('buystatus',C('buyStatus'));
    }

    public function _before_edit() {
        $this->assign('logicompany',C('chinalogi'));
        $this->assign('buystatus',C('buyStatus'));
        $this->assign('his_offers',M('Ask_supplier_detail')->where('product_id = '.getModelName($_REQUEST['id'],'Buy','product_id') ) ->order('status desc')->findAll() );
    }

    public function _before_insert()
    {
        //总价,如果为空，则自动计算
        if(empty($_POST['total']))
            $_POST['total'] = $_POST['number']*$_POST['price'];
        //通过采购订单号流转来的采购任务
        if(!empty($_REQUEST['order_detail_id']))
            M('Order_detail')->where('id = '.$_REQUEST['order_detail_id'])->setField('status',1); //已发布采购任务后，小订单状态变为库存不足，待采购

    }
   
   function update($field='name') {
        //B('FilterString');
        $name='Buy';
        $model = D ( $name );
        $id = intval($_POST['id']);
       
        $old = $model->where('id = '.$id)->find();
        $new_supplier_id = 0; //new supplier
        //判断是否更换了供应商
        if($old['supplier_id'] != 0 && !empty($_POST['supplier_id'])  
            && $old['supplier_id'] != $_POST['supplier_id'] ){
            
            $_POST['status'] = 10; //置状态为作废
            $new_supplier_id = $_POST['supplier_id'];
            $_POST['supplier_id'] = $old['supplier_id'];  //保持原供应商不变
        }

        //如果已经确认了供应商//只有要单价，则采购成本不得高于对应销售订单中的采购成本  TODO
        if(/* $old['status'] > 1 &&*/ $old['order_detail_id'] > 0 && !empty($_POST['price']) ){
            $sale_cost = getModelName( $old['order_detail_id'],'Order_detail','cost' );
            if($_POST['price'] > $sale_cost )
                $this->error('采购价过高！');
        }

        if(!empty($_POST['price']) && !empty($_POST['number']) )
            $_POST['total'] = $_POST['price'] * $_POST['number'];
        if(!empty($_POST['to_first_pay'])){
            if(!empty($_POST['total']))
                 $_POST['to_remain_pay'] = $_POST['total'] - $_POST['to_first_pay'];
             else
                $_POST['to_remain_pay'] = $old['total'] - $_POST['to_first_pay'];
        }
           
           
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        // 更新数据
        $list=$model->save ();
        if (false !== $list) {
            $new = $model->where('id = '.$id)->find();

            $odvalue = 0;   //  order_detail new status value
            //采购中
            if( $new['status'] > 0 && $new['status'] < 8 )
                $odvalue = 2;
            /*
            else if($new['status'] == 8 )  //到货通知由仓库操作，此处不操作。此处易引起状态返回
                $odvalue = 3;   //到货通知 */
            if($odvalue != 0)
                M('Order_detail')->where('id = '.$old['order_detail_id'])->setField('status',$odvalue);
            //更新实际付款之和 实际付款= 预付款 + 余款-退款
            $oldbuy = M('Buy')->getById($_POST['id']);
            M('Buy')->where('id ='.$_POST['id'])->setField('real_pay',($oldbuy['first_pay'] + $oldbuy['remain_pay']-$oldbuy['back_money']) );

                   
            
            
            //若更换了供应商，则自动创建新的采购单，同时状态为签订合同中==2
            if($new_supplier_id != 0 ){
                $newBuy = $new;
                $newBuy['id'] = M('Buy')->max('id')+1; 
                $newBuy['supplier_id'] = $new_supplier_id;
                $newBuy['order_detail_id'] = $new['order_detail_id'];
                $newBuy['mano'] = D('Buy') -> getNO();
                $newBuy['create_time'] = $newBuy['update_time'] = time(); 
                $newBuy['status'] = 2; //和供应商签订合同
                $newBuy['pay_status'] = 0; //付款状态变为待确定
                $model ->add($newBuy);
            }

            //记录日志
            $mod_field = getModelName ($id, $name,$field);
            //如果未取到字段值 ，则返回对应的ID编号
            $msg = '修改 '.$name.': '.$mod_field.' (编号：'.$id.')';
            if('Action' != $name)
                A('Action')->writeLog($msg,'修改',$name,$id,$old,$new);
            //成功提示
            $jumpUrl = empty($_REQUEST['jumpUrl']) ? Cookie::get('_currentUrl_') : $_REQUEST['jumpUrl']; 
            $this->assign ( 'jumpUrl', $jumpUrl );
            $this->success ('编辑成功!');
        } else {
            //错误提示
            $this->error ('编辑失败!');
        }
    }

    //目前暂用于批量更改送检物流信息
    public function mass_update()
    {
         $data = $_POST;
        $count_no = count($data['id']);
        for($i =0; $i < $count_no;$i++) {
          $_POST['id'] =  $data['id'][$i];
          if(!empty($data['sample_qc_status'][$i])){
            $_POST['sample_qc_status'] = $data['sample_qc_status'][$i];
            if($_POST['sample_qc_status'] == 2 ) //如果是样品送检中
                $_POST['sample_to_test_time'] = time(); //记录检品送检时间
            else if($_POST['sample_qc_status'] == 6 ) //如果是样品已经收到
                $_POST['sample_got_time'] = time(); //记录检品收到时间
          }
          if(!empty($data['sample_test_loginfo'][$i]))
            $_POST['sample_test_loginfo'] = $data['sample_test_loginfo'][$i];
          if(!empty($data['in_qc_status'][$i]))
            $_POST['in_qc_status'] = $data['in_qc_status'][$i];
          if(!empty($data['goods_test_loginfo'][$i]))
            $_POST['goods_test_loginfo'] = $data['goods_test_loginfo'][$i];
        //批量指定负责人
        if(!empty($data['charge_man'][$i]))
            $_POST['charge_man'] = $data['charge_man'][$i];
        
            $this->micro_update($_POST['id']);

          unset($_POST);
        }

        $jumpUrl = $_REQUEST['jumpUrl'];
        if(empty($jumpUrl))
            $jumpUrl = Cookie::get ( '_currentUrl_' );
        $this->assign ( 'jumpUrl', $jumpUrl );
        $this->success ('批量修改成功!');
    }

    //分配责任人
    public function charge()
    {
        $id = $_REQUEST['id'];
        if (isset ( $id )) {
          
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $list = M('Buy') ->where ( $condition )->findAll();
            $sale_ids = array(); //有效的SALE_ID
            if(!is_array($list))
                $this->error('您选择的采购单不存在！');
            $this->assign('receives',$list);
            $this->display();
        }else
          $this->error("请选择采购单！");
    }

  public function createBuyConsign(){
      $id = $_REQUEST['id'];    
      $buy = D('BuyOrderView')->where('Buy.id ='.$id)->find();
      if(!is_array($buy))
          $this->error('请选择有效的采购订单！');

     $print_date = toDate(time(),'Y年m月d日');
     $valid_date = toDate(time()+60*60*24*364,'Y年m月d日');
     $rmb = toCNcap($buy['total']);//转为人民币大写

        import('@.ORG.PHPWord','','.php');
        spl_autoload_register(array('Think','autoload'));   //必须重置，否则造成原TP类无法识别
        $PHPWord = new PHPWord();
        $public_dir =$_SERVER[DOCUMENT_ROOT].__ROOT__.'/Public';
        $save_name = "采购合同_".$buy['order_detail_mano'].".docx";

        $document = $PHPWord->loadTemplate($public_dir.'/Uploads/buy_consign.docx');
        $document->setValue('supplier', $buy['sname']);
        $document->setValue('order_detail_mano', $buy['order_detail_mano']);
        $document->setValue('print_date',$print_date);
        $document->setValue('valid_date',$valid_date);
        $document->setValue('pname',$buy['pname']);
        $document->setValue('pename',$buy['pename']);
        $document->setValue('cas',$buy['cas']);

        $specification = getModelName( $buy['specification'],'Specification' );
        $document->setValue('specification',$specification);
        $document->setValue('number',$buy['number'] );
        $document->setValue('total',$buy['total'] );
        $document->setValue('rmb',$rmb );
        $document->setValue('delivery_date',toDate($buy['delivery_date']-5*60*60*24,'Y年m月d日' )); //比系统中的交货期早5天
        $document->setValue('settle_method',getConfigVal($buy['settle_method'],'settle_method') );
        
        $supplier = M('Supplier')->getById($buy['supplier_id']);
        $document->setValue('address',$supplier['address'] );
        $document->setValue('fax',$supplier['fax'] );
        $document->setValue('phone',$supplier['phone'] );


        $document->save($public_dir.'/Downloads/buy/'.$save_name);
        $this->success("采购合同成功生成，请返回下载打印"); 
  }
    
}
?>
